/*
 Copyright (C) 2012 Mattias Ugelvik

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function get_country(country) {
    return nations.find(function(elem) {
        return elem['name'] === country;
    });
}

function readable(set) {
    return Array.from(set).join(', ');
}

function complete(request, response) {
    var result = [],
        reg = new RegExp('\\b' + $.ui.autocomplete.escapeRegex(request.term), 'i');
    
    for (country of nations) {
        for (name of [country['name'], ...country['other_names']]) {
            if (reg.test(name)) {
                result.push(country['name']);
                break;
            }
        }
    }
    response(result);
}

$(document).ready(function() {
    var names = new Set(nations.map(function(nation) {
        return nation['name'];
    }));

    var current_country,
        get_current = function() {
            return new Set($('.choice').map(function() {
                return $(this).html();
            }).get());
        },
        get_answer = function() {
            return new Set(current_country['bordernations']);
        };

    $('#input').autocomplete({
        source: complete,
        autoFocus: true,
        select: function(event, ui) {
            add_input(ui.item.value);
            return false;
        }
    });

    function add_input(default_val) {
        var val = default_val || $('#input').val();
        
        if (!get_current().has(val) && names.has(val)) {
            $('#choices').append($('<li class=choice>' + val + '</li>').click(
                function (event) { $(this).remove(); }
            ));
            $('#input').val('');
        }
        else if (get_current().has(val)) {
            $('.choice').filter(function (idx) {
                return $(this).html() === val;
            }).remove();
            $('#input').val('');
        }
    }

    $('#input').keypress(function (event) {
        if (event.which === 13) {
            if ($('#input').val() === '') $('#answer-button').click();
            else add_input();
        }
    });

    $('#report #new-game').click(function () { start_game(); });

    function start_game(starting_country) {
        current_country = get_country(starting_country) ||
            nations[Math.floor(Math.random() * nations.length)];

        $('#choices').empty();
        $('#input').val('');
        
        $('#report').hide();        
        $('#game-area').show();
        
        $('#left p').html(current_country['meta']);
        $('#current-country').html(current_country['name']).attr('title', current_country['code']);
        $('#input').focus();
    }


    $('#answer-button').click(function () {
        var current = get_current(),
            answer  = get_answer();
        
        correct_guesses = Array.from(current).filter(function (value) {
            return answer.has(value); });
        incorrect_guesses = Array.from(current).filter(function (value) {
            return !answer.has(value); });
        missed = Array.from(answer).filter(function (value) {
            return !current.has(value); });

        $('#report p').hide();
        new Map([["correct",   correct_guesses],
                 ["incorrect", incorrect_guesses],
                 ["missed",    missed]]).forEach(function(set, name) {
                     if (set.length > 0)
                         $('#report #' + name).html(readable(set)).parent().show();
                 });
        
        if (incorrect_guesses.length + missed.length === 0)
            $('#report h1').html('Correct!');
        else
            $('#report h1').html('You suck!');
        
        $('#game-area').hide();
        $('#report').show();
        
        $('#report #new-game').focus();
    });

    start_game(getParameterByName('country'));

});
